/*
 * Iwire.h
 *
 *  Created on: 21.02.2013
 *      Author: Roma Jam
 */

#ifndef IWIRE_H_
#define IWIRE_H_

#include "kl_lib.h"
#include "timer.h"
#include "string.h"

#define SIZE_OF_DATA            99
#define SIZE_OF_ROM             8
#define UART2_TX                GPIO_Pin_2
#define UART2_RX                GPIO_Pin_3
#define UART2_GPIO              GPIOA

// CMD's
// Service
#define CMD_SET_DATA_MODE       0xE1
#define CMD_SET_CMD_MODE        0xE3
// Initialize
#define CMD_RESET               0xC1
#define CMD_RESET_FLEX          0xC5
#define CMD_READ_ROM            0x33
#define CMD_MATCH_ROM           0x55
#define CMD_SEARCH_ROM          0xF0
#define CMD_ALARM_SEARH         0xEC
#define CMD_SKIP_ROM            0xCC
// Functions
#define CMD_CONVERT_T           0x44
#define CMD_COPY_SCRATCHPAD     0x48
#define CMD_WRITE_SCRATCHPAD    0x4E
#define CMD_READ_SCRATCHPAD     0xBE
#define CMD_RECALL_E2           0xB8
#define CMD_READ_POWER_SUPPLY   0xB4


enum IWireState_t { iwsIdle, iwsPresence, iwsBusy, iwsWaitAnsw, iwsReadyToConv, iwsRxTemp, iwsAbsent };
enum SensorSpeed_t {
    ssReg   = 0x00,
    ssFlex  = 0x04,
    ssOD    = 0x08
};
struct IWire_t {
private:
    uint8_t ByteCRC;
    uint8_t Data;
    uint8_t Count;
    IWireState_t State;
    uint8_t RXBuf[SIZE_OF_DATA];
    uint8_t WriteIndx, ReadIndx;
    uint32_t Timer;
    void BufInit()  { memset(PRXBuf, 0, SIZE_OF_DATA); WriteIndx = 0; ReadIndx = 0; }
    uint8_t Read()  { uint8_t AByte = PRXBuf[ReadIndx++]; if(ReadIndx > (SIZE_OF_DATA - 1)) ReadIndx = 0; return AByte; }
    bool WasRead()  { return (WriteIndx == ReadIndx); }

    // DS2480
    void Reset()    { USART_SendData(USART2, CMD_RESET_FLEX); while (USART_GetFlagStatus(USART2, USART_FLAG_TC) == RESET); }

public:
    SensorSpeed_t Speed;
    uint8_t *PRXBuf, *PIndex;
    Timer_t IWireTimer;
    uint16_t Temperature;
    void Write(uint8_t AByte)   { PRXBuf[++(*PIndex)] = AByte; if((*PIndex) > SIZE_OF_DATA - 1) *PIndex = 0; }
    void Task(void);
    void Init(void);
    void ReInit(uint32_t AValue);
    void Cmd(uint8_t CMD);
    void SendService(uint8_t AByte);
};

extern IWire_t IWire;

extern "C"{
    void USART2_IRQHandler(void);
}

#endif /* IWIRE_H_ */
